package thinking.in.spring.ioc.overview.container;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import thinking.in.spring.ioc.overview.domain.User;

import java.util.Map;

/**
 * 注解的 {@link ApplicationContext} 作为 IoC 容器示例
 *
 * @author Ringo
 * @date 2021/8/22 21:23
 */
public class AnnotationApplicationContextAsIocContainerDemo {

    public static void main(String[] args) {
        // 1: 创建 ApplicationContext 作为 IoC 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 2: 将当前类注册为 Configuration 类
        applicationContext.register(AnnotationApplicationContextAsIocContainerDemo.class);
        // 3: 调用 refresh() 启动应用上下文
        applicationContext.refresh();
        // 4: IoC 容器中找 Bean
        Map<String, User> users = applicationContext.getBeansOfType(User.class);
        System.out.println("IoC 容器中查找到的User Bean: " + users);
    }

    /**
     * 通过 Java 注解的方式定义 Bean
     */
    @Bean
    public User user() {
        User user = new User();
        user.setId(10L);
        user.setName("zs");
        return user;
    }
}
